#include "tcpserver.h"

#include <QMessageBox>
#include <QDebug>

TcpServer::TcpServer(QObject *parent): TcpBase{parent}{
    server = new QTcpServer();
    serverState = SERVER_IDLE;
    source = FromServer;
}

bool TcpServer::listenToConnect(QHostAddress addr, int port){
    bool state = server->listen(addr, port);
    if(state && serverState == SERVER_IDLE){
        connect(server, SIGNAL(newConnection()), this, SLOT(onNewConnectFromClient()));
        serverState = SERVER_LISTENING;
    }
    return state;
}

bool TcpServer::stopListen(){
    disconnect(server, SIGNAL(newConnection()), this, SLOT(onNewConnectFromClient()));
    server->disconnect();
    server->close();
    serverState = SERVER_IDLE;
    return true;
}

void TcpServer::onNewConnectFromClient(){
    socket = server->nextPendingConnection();
    connect(socket, SIGNAL(readyRead()), this, SLOT(onRecvMsg()));
    connect(socket, SIGNAL(errorOccurred(QAbstractSocket::SocketError)),this, SLOT(socketErrorHandler(QAbstractSocket::SocketError)));

    QString ip = socket->peerAddress().toString().split("::ffff:")[1];
    quint16 port = socket->peerPort();

    CommonMessage msg = CommonMessage(NewConnection, ip+":"+QString::number((int)port));
    emit sendMsgToMain(source, msg);
}





